<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>权限管理 - 新疆奎木星测控技术有限公司</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f7fa;
            color: #333;
        }
        
        .page-container {
            padding: 20px;
            min-height: 100vh;
        }
        
        .page-header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .page-title {
            font-size: 24px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
        }
        
        .page-subtitle {
            color: #7f8c8d;
            font-size: 14px;
        }
        
        .content-layout {
            display: grid;
            grid-template-columns: 1fr 2fr;
            gap: 20px;
        }
        
        .content-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .card-header {
            padding: 20px;
            border-bottom: 1px solid #ebeef5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .card-title {
            font-size: 18px;
            font-weight: 500;
            color: #2c3e50;
        }
        
        .card-content {
            padding: 20px;
        }
        
        .role-item {
            padding: 12px 16px;
            border: 1px solid #e4e7ed;
            border-radius: 6px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .role-item:hover {
            border-color: #409eff;
            background: #f0f9ff;
        }
        
        .role-item.active {
            border-color: #409eff;
            background: #ecf5ff;
        }
        
        .role-info {
            flex: 1;
        }
        
        .role-name {
            font-weight: 500;
            color: #2c3e50;
            margin-bottom: 4px;
        }
        
        .role-desc {
            font-size: 12px;
            color: #909399;
        }
        
        .role-actions {
            display: flex;
            gap: 8px;
        }
        
        .permission-tree {
            max-height: 600px;
            overflow-y: auto;
        }
        
        .permission-section {
            margin-bottom: 20px;
        }
        
        .section-title {
            font-size: 16px;
            font-weight: 500;
            color: #2c3e50;
            margin-bottom: 12px;
            padding: 8px 0;
            border-bottom: 1px solid #ebeef5;
        }
        
        .permission-group {
            margin-left: 20px;
            margin-bottom: 16px;
        }
        
        .group-title {
            font-weight: 500;
            color: #606266;
            margin-bottom: 8px;
        }
        
        .permission-item {
            margin-left: 20px;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .permission-desc {
            color: #909399;
            font-size: 12px;
            margin-left: 4px;
        }
        
        .save-actions {
            padding: 20px;
            border-top: 1px solid #ebeef5;
            text-align: right;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 20px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }
        
        .stat-card.green {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        .stat-card.orange {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        }
        
        .stat-card.red {
            background: linear-gradient(135deg, #ff6b6b 0%, #ffa726 100%);
        }
        
        .stat-number {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .stat-label {
            font-size: 14px;
            opacity: 0.9;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="page-container">
            <!-- 页面头部 -->
            <div class="page-header">
                <h1 class="page-title">
                    <i class="fas fa-shield-alt"></i> 权限管理
                </h1>
                <p class="page-subtitle">管理系统角色权限配置和访问控制</p>
            </div>
            
            <!-- 统计卡片 -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-number">{{ roles.length }}</div>
                    <div class="stat-label">系统角色</div>
                </div>
                <div class="stat-card green">
                    <div class="stat-number">{{ totalPermissions }}</div>
                    <div class="stat-label">权限节点</div>
                </div>
                <div class="stat-card orange">
                    <div class="stat-number">{{ activeRoles }}</div>
                    <div class="stat-label">启用角色</div>
                </div>
                <div class="stat-card red">
                    <div class="stat-number">{{ adminRoles }}</div>
                    <div class="stat-label">管理员角色</div>
                </div>
            </div>
            
            <!-- 主要内容区域 -->
            <div class="content-layout">
                <!-- 角色列表 -->
                <div class="content-card">
                    <div class="card-header">
                        <h2 class="card-title">角色列表</h2>
                        <el-button type="primary" size="small" @click="showRoleDialog = true">
                            <i class="fas fa-plus"></i> 新增角色
                        </el-button>
                    </div>
                    <div class="card-content">
                        <div 
                            v-for="role in roles" 
                            :key="role.id" 
                            :class="['role-item', { active: selectedRole?.id === role.id }]"
                            @click="selectRole(role)"
                        >
                            <div class="role-info">
                                <div class="role-name">{{ role.role_name }}</div>
                                <div class="role-desc">{{ role.description }}</div>
                            </div>
                            <div class="role-actions">
                                <el-button size="small" type="text" @click.stop="editRole(role)">
                                    <i class="fas fa-edit"></i>
                                </el-button>
                                <el-button size="small" type="text" @click.stop="deleteRole(role)" v-if="role.code !== 'admin'">
                                    <i class="fas fa-trash" style="color: #f56c6c;"></i>
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 权限配置 -->
                <div class="content-card">
                    <div class="card-header">
                        <h2 class="card-title">
                            权限配置 
                            <span v-if="selectedRole" style="color: #909399; font-size: 14px; font-weight: normal;">
                                - {{ selectedRole.role_name }}
                            </span>
                        </h2>
                        <el-button type="success" size="small" @click="savePermissions" v-if="selectedRole">
                            <i class="fas fa-save"></i> 保存权限
                        </el-button>
                    </div>
                    <div class="card-content" v-if="selectedRole">
                        <div class="permission-tree">
                            <el-tree
                                :data="menuList"
                                :props="{ children: 'children', label: 'menu_name' }"
                                show-checkbox
                                node-key="id"
                                :default-expanded-keys="[1, 5, 10, 15]"
                                :default-checked-keys="selectedRole ? selectedRole.permissions : []"
                                ref="permissionTree"
                                @check="handlePermissionCheck"
                            >
                                <template #default="{ node, data }">
                                    <div class="permission-node">
                                        <span class="permission-name">{{ data.menu_name }}</span>
                                        <span v-if="data.description" class="permission-desc">{{ data.description }}</span>
                                    </div>
                                </template>
                            </el-tree>
                        </div>
                    </div>
                    <div class="card-content" v-else>
                        <el-empty description="请选择一个角色来配置权限"></el-empty>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 角色编辑对话框 -->
        <el-dialog v-model="showRoleDialog" :title="editingRole ? '编辑角色' : '新增角色'" width="500px">
            <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="80px">
                <el-form-item label="角色名称" prop="role_name">
                    <el-input v-model="roleForm.role_name" placeholder="请输入角色名称"></el-input>
                </el-form-item>
                <el-form-item label="角色编码" prop="code">
                    <el-input v-model="roleForm.code" placeholder="请输入角色编码" :disabled="editingRole"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                    <el-input v-model="roleForm.description" type="textarea" placeholder="请输入角色描述"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="roleForm.status">
                        <el-radio label="active">启用</el-radio>
                        <el-radio label="inactive">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showRoleDialog = false">取消</el-button>
                    <el-button type="primary" @click="saveRole">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
    
    <script>
        const { createApp } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;
        
        createApp({
            data() {
                return {
                    // 选中的角色
                    selectedRole: null,
                    // 对话框显示状态
                    showRoleDialog: false,
                    editingRole: null,
                    // 角色表单数据
                    roleForm: {
                        role_name: '',
                        code: '',
                        description: '',
                        status: 'active'
                    },
                    // 表单验证规则
                    roleRules: {
                        role_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
                        code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }]
                    },
                    // 角色列表（基于Role表结构）
                    roles: [
                        {
                            id: 1,
                            role_name: '系统管理员',
                            code: 'admin',
                            description: '拥有系统所有权限',
                            status: 'active',
                            permissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] // 所有菜单权限
                        },
                        {
                            id: 2,
                            role_name: '数据分析员',
                            code: 'analyst',
                            description: '负责数据分析和报表生成',
                            status: 'active',
                            permissions: [10, 11, 12, 13, 14, 15, 16, 17, 18] // 数据查询和报表权限
                        },
                        {
                            id: 3,
                            role_name: '业务操作员',
                            code: 'operator',
                            description: '负责日常业务操作和数据录入',
                            status: 'active',
                            permissions: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] // 组织管理和业务管理权限
                        },
                        {
                            id: 4,
                            role_name: '数据查看员',
                            code: 'viewer',
                            description: '只能查看数据，无编辑权限',
                            status: 'active',
                            permissions: [15, 16, 17, 18] // 仅查看权限
                        },
                        {
                            id: 5,
                            role_name: '集团管理员',
                            code: 'group_admin',
                            description: '管理特定集团的数据和用户',
                            status: 'active',
                            permissions: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] // 集团相关权限
                        }
                    ],
                    // 基于Menu表结构的权限数据
                    menuList: [
                        {
                            id: 1,
                            menu_name: '系统管理',
                            description: '系统基础管理功能',
                            children: [
                                { id: 2, menu_name: '用户管理', description: '管理系统用户账户' },
                                { id: 3, menu_name: '角色管理', description: '管理用户角色权限' },
                                { id: 4, menu_name: '菜单管理', description: '管理系统菜单结构' }
                            ]
                        },
                        {
                            id: 5,
                            menu_name: '组织管理',
                            description: '管理组织架构信息',
                            children: [
                                { id: 6, menu_name: '省/兵团管理', description: '管理省份和兵团信息' },
                                { id: 7, menu_name: '市级管理', description: '管理市级行政区域' },
                                { id: 8, menu_name: '区县管理', description: '管理区县级行政区域' },
                                { id: 9, menu_name: '乡镇管理', description: '管理乡镇级行政区域' }
                            ]
                        },
                        {
                            id: 10,
                            menu_name: '业务管理',
                            description: '核心业务功能管理',
                            children: [
                                { id: 11, menu_name: '集团管理', description: '管理集团信息' },
                                { id: 12, menu_name: '加工厂管理', description: '管理加工厂信息' },
                                { id: 13, menu_name: '农户管理', description: '管理农户基础信息' },
                                { id: 14, menu_name: '地块管理', description: '管理农田地块信息' }
                            ]
                        },
                        {
                            id: 15,
                            menu_name: '数据统计',
                            description: '数据统计和报表功能',
                            children: [
                                { id: 16, menu_name: '收购统计', description: '粮食收购数据统计' },
                                { id: 17, menu_name: '销售统计', description: '粮食销售数据统计' },
                                { id: 18, menu_name: '库存统计', description: '库存数据统计分析' }
                            ]
                        }
                    ],
                    // 权限结构（基于菜单结构生成）
                    permissionSections: []
                }
            },
            
            computed: {
                // 总权限数（基于菜单结构计算）
                totalPermissions() {
                    let count = 0;
                    const countMenus = (menus) => {
                        menus.forEach(menu => {
                            count++;
                            if (menu.children) {
                                countMenus(menu.children);
                            }
                        });
                    };
                    countMenus(this.menuList);
                    return count;
                },
                
                // 启用的角色数
                activeRoles() {
                    return this.roles.filter(role => role.status === 'active').length;
                },
                
                // 管理员角色数（拥有所有权限的角色）
                adminRoles() {
                     return this.roles.filter(role => {
                         return this.allMenuIds.every(id => role.permissions.includes(id));
                     }).length;
                 },
                
                // 获取所有菜单ID（包括子菜单）
                allMenuIds() {
                    const ids = [];
                    const collectIds = (menus) => {
                        menus.forEach(menu => {
                            ids.push(menu.id);
                            if (menu.children && menu.children.length > 0) {
                                collectIds(menu.children);
                            }
                        });
                    };
                    collectIds(this.menuList);
                    return ids;
                }
            },
            
            methods: {

                
                // 编辑角色
                editRole(role) {
                    this.editingRole = role;
                    this.roleForm = { ...role };
                    this.showRoleDialog = true;
                },
                
                // 删除角色
                deleteRole(role) {
                    ElMessageBox.confirm(
                        `确定要删除角色 "${role.role_name}" 吗？`,
                        '删除确认',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    ).then(() => {
                        const index = this.roles.findIndex(r => r.id === role.id);
                        if (index > -1) {
                            this.roles.splice(index, 1);
                            if (this.selectedRole?.id === role.id) {
                                this.selectedRole = null;
                            }
                            ElMessage.success('角色删除成功');
                        }
                    }).catch(() => {
                        ElMessage.info('已取消删除');
                    });
                },
                
                // 保存角色
                saveRole() {
                    this.$refs.roleFormRef.validate((valid) => {
                        if (valid) {
                            if (this.editingRole) {
                                // 编辑模式
                                const index = this.roles.findIndex(r => r.id === this.editingRole.id);
                                if (index > -1) {
                                    this.roles[index] = { ...this.roleForm, id: this.editingRole.id, permissions: this.editingRole.permissions };
                                    ElMessage.success('角色更新成功');
                                }
                            } else {
                                // 新增模式
                                const newRole = {
                                    ...this.roleForm,
                                    id: Math.max(...this.roles.map(r => r.id)) + 1,
                                    permissions: []
                                };
                                this.roles.push(newRole);
                                ElMessage.success('角色创建成功');
                            }
                            
                            this.showRoleDialog = false;
                            this.editingRole = null;
                            this.resetRoleForm();
                        }
                    });
                },
                
                // 重置角色表单
                resetRoleForm() {
                    this.roleForm = {
                        role_name: '',
                        code: '',
                        description: '',
                        status: 'active'
                    };
                },
                
                // 获取所有菜单ID
                getAllMenuIds(menus) {
                    let ids = [];
                    menus.forEach(menu => {
                        ids.push(menu.id);
                        if (menu.children) {
                            ids = ids.concat(this.getAllMenuIds(menu.children));
                        }
                    });
                    return ids;
                },
                
                // 刷新权限树的选中状态
                refreshPermissionTree() {
                    this.$nextTick(() => {
                        if (this.$refs.permissionTree && this.selectedRole) {
                            this.$refs.permissionTree.setCheckedKeys(this.selectedRole.permissions);
                        }
                    });
                },
                
                // 处理权限树的选择变化
                handlePermissionCheck(data, checkedInfo) {
                    if (!this.selectedRole) return;
                    
                    // 获取所有选中的节点ID（包括半选中的父节点）
                    const checkedKeys = checkedInfo.checkedKeys;
                    const halfCheckedKeys = checkedInfo.halfCheckedKeys;
                    
                    // 更新角色权限
                    this.selectedRole.permissions = [...checkedKeys, ...halfCheckedKeys];
                },
                
                // 选择角色时刷新权限树
                selectRole(role) {
                    this.selectedRole = role;
                    this.refreshPermissionTree();
                },
                
                // 保存权限
                savePermissions() {
                    ElMessage.success(`角色 "${this.selectedRole.role_name}" 的权限配置已保存`);
                }
            },
            
            mounted() {
                // 默认选择第一个角色
                if (this.roles.length > 0) {
                    this.selectedRole = this.roles[0];
                }
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>